package com.ljc.cjgl.controller;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.HashSet;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.abyss.data.specifications.Rule;
import org.apache.tomcat.util.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.ljc.cjgl.custom.FileUtil;
import com.ljc.cjgl.custom.TablePageable;
import com.ljc.cjgl.custom.TableResult;
import com.ljc.cjgl.entitiy.TbImage;
import com.ljc.cjgl.service.ImageService;

@Controller
@RequestMapping(value="/image")
public class ImageController {
	@Autowired
	private ImageService service;
	
	//跳转到上传文件的页面
    @RequestMapping(value="/manage", method = RequestMethod.GET)
    public String goUploadImg() {
        return "image/manage";
    }
    
    @RequestMapping(value="/page",method= RequestMethod.GET)
    @ResponseBody
    public Object page(String search,TablePageable pageable,TbImage image) {
    	PageRequest pageRequest=pageable.bulidPageRequest();
    	String filename = image.getFilename();
    	String title = image.getTitle();
    	HashSet<Rule> rules=new HashSet<>();
    	if(StringUtils.hasText(filename)) {
    		rules.add(Rule.property("filename").contain(filename));
    	}
    	if(StringUtils.hasText(title)) {
    		rules.add(Rule.property("title").contain(title));
    	}
    	if(StringUtils.hasText(search)) {
    		HashSet<Rule> rules2=new HashSet<>();
    		rules2.add(Rule.property("title").contain(search));
    		rules2.add(Rule.property("demo").contain(search));
    		rules2.add(Rule.property("filename").contain(search));
    		rules.add(Rule.or(rules2));
    	}
    	Page<TbImage> page=service.findAll(Rule.and(rules).toSpecification(),pageRequest);
    	return TableResult.bulidPageResult(page);
    }
    
    @RequestMapping(value="/edit")
    public String edit(Integer id,ModelMap map) {
    	TbImage image=new TbImage();
    	if(id!=null) {
    		image=service.findOne(id);
    	}
    	map.put("model",image);
    	return "image/edit";
    }
    
    //处理文件上传
    @RequestMapping(value="/save", method = RequestMethod.POST)
    @ResponseBody
    public Object uploadImg(@RequestParam("file") MultipartFile file,TbImage image,
            HttpServletRequest request) throws IOException {
    	
    	service.save(file,image);
    	return TableResult.bulidResult(true, "数据保存成功");
    }
    
    /***
     * 将下载的文件名改成能够在网上传送的字符串
     * @param request 请求对象
     * @param fileName 文件名
     * @return
     */
    public String getStr(HttpServletRequest request, String fileName) {
        String downloadFileName = null;
        String agent = request.getHeader("USER-AGENT");
        try {
            if (agent != null && agent.toLowerCase().indexOf("firefox") > 0) {
                downloadFileName = "=?UTF-8?B?" + (new String(Base64.encodeBase64(fileName.getBytes("UTF-8")))) + "?=";
            } else {
                downloadFileName = java.net.URLEncoder.encode(fileName, "UTF-8");
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return downloadFileName;
    }
    
    @RequestMapping(value="/download")
    @ResponseBody
    public Object download(HttpServletRequest request,HttpServletResponse response, Integer id,String uid) {
    	TbImage image;
    	if(id!=null) {
    		image=service.findOne(id);
    	}else {
    		image=service.findByUid(uid);
    	}
    	String targetName=image.getFilename();
    	String sourceName=image.getUid();
    	FileUtil.download(request,response,sourceName,targetName);
    	return null;
    }
    
    @RequestMapping(value="/delete")
    @ResponseBody
    public Object delete(@RequestBody List<TbImage> images) {
    	try {
    		service.delete(images);
    		return TableResult.bulidResult(true, "数据删除成功");
		} catch (Exception e) {
			return TableResult.bulidResult(false, "数据删除失败");
		}
    }

}
